/*
 * libustream: User-space stackable streams
 * @(#) $Id: fd.c 2 2009-02-20 09:52:11Z mo@ilaven.net $
 */

/*
 * Copyright (c) 2002, 2008 Mo McRoberts.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The names of the author(s) of this software may not be used to endorse
 *    or promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * AUTHORS OF THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "p_usmodules.h"

/* This module implements stream head support for disk files */

static com_result_t __stdcall UStream_FD_QueryInterface(IUStreamNode *intf, com_riid_t iid, void **out);
static uint32_t __stdcall UStream_FD_AddRef(IUStreamNode *intf);
static uint32_t __stdcall UStream_FD_Release(IUStreamNode *intf);
static com_result_t __stdcall UStream_FD_GetChildNode(IUStreamNode *intf, IUStream *parent, IUStream *child, IUStreamNode **childNode);
static com_result_t __stdcall UStream_FD_Write(IUStreamNode *intf, IUStream *stream, const void *buf, size_t *buflen);
static com_result_t __stdcall UStream_FD_Read(IUStreamNode *intf, IUStream *stream, void *buf, size_t *buflen);
static com_result_t __stdcall UStream_FD_Pending(IUStreamNode *intf, IUStream *stream, size_t *out);
static com_result_t __stdcall UStream_FD_Accept(IUStreamNode *intf, IUStream *stream, IUStreamNode **out, int *fdout);

DECLARE_CLASS(UStream_FD)
{
	DECLARE_IMPLEMENTS(UStream_FD, IUStreamNode);
	uint32_t refcount;
	int fd;
};

DEFINE_CLASS_INTERFACE(UStream_FD, IUStreamNode)
{
	UStream_FD_QueryInterface,
	UStream_FD_AddRef,
	UStream_FD_Release,
	UStream_FD_GetChildNode,
	UStream_FD_Write,
	UStream_FD_Read,
	UStream_FD_Pending,
	UStream_FD_Accept
};

extern com_result_t
us__fd_open(const iri_t *iri, int oflag, mode_t mode, IUStreamNode **out, int *fdout)
{
	UStream_FD *f;
	const char *s;
	char *p;

	(void) oflag;
	(void) mode;
	
	if(NULL == (s = iri->path) || '/' != s[0] || 0 == s[1])
	{
		return EINVAL;
	}
	s++;
	if(NULL == (f = (UStream_FD *) calloc(1, sizeof(UStream_FD))))
	{
		return errno;
	}
	p = NULL;
	if(0 == strcmp(s, "stdin"))
	{
		f->fd = 0;
	}
	else if(0 == strcmp(s, "stdout"))
	{
		f->fd = 1;
	}
	else if(0 == strcmp(s, "stderr"))
	{
		f->fd = 2;
	}
	else
	{
		f->fd = (int) strtol(s, &p, 0);
		if(p && p[0])
		{
			free(f);
			return EINVAL;
		}
	}
	if(f->fd < 0)
	{
		free(f);
		return EBADF;
	}
	INITIALISE_ADDREF_INTERFACE_POINTER(UStream_FD, f, IUStreamNode);
	*out = GET_INTERFACE_POINTER(f, IUStreamNode);
	*fdout = f->fd;
	return COM_S_OK;
}

static com_result_t __stdcall
UStream_FD_QueryInterface(IUStreamNode *intf, com_riid_t iid, void **out)
{
	if(com_guid_equal(iid, &IID_IUnknown) || com_guid_equal(iid, &IID_IUStreamNode))
	{
		UStream_FD_AddRef(intf);
		*out = (void *) intf;
		return COM_S_OK;
	}
	return COM_E_NOINTERFACE;
}

static uint32_t __stdcall
UStream_FD_AddRef(IUStreamNode *intf)
{
	DECLARE_SELF(UStream_FD, IUStreamNode, intf);
	
	self->refcount++;
	return self->refcount;
}

static uint32_t __stdcall
UStream_FD_Release(IUStreamNode *intf)
{
	DECLARE_SELF(UStream_FD, IUStreamNode, intf);
	
	self->refcount--;
	if(0 == self->refcount)
	{
/*		fprintf(stderr, "Closing the file\n"); */
		if(self->fd != -1)
		{
			/* As with fdopen(), we close the descriptor when the stream
			 * is released.
			 */
			close(self->fd);
		}
		free(self);
		return 0;
	}
	return self->refcount;
}

static com_result_t __stdcall
UStream_FD_GetChildNode(IUStreamNode *intf, IUStream *parent, IUStream *child, IUStreamNode **childNode)
{
	(void) intf;
	(void) parent;
	(void) child;
	(void) childNode;
	
	return COM_E_NOT_SUPPORTED;
}


static com_result_t __stdcall
UStream_FD_Write(IUStreamNode *intf, IUStream *stream, const void *buf, size_t *buflen)
{
	ssize_t r;

	DECLARE_SELF(UStream_FD, IUStreamNode, intf);

	(void) stream;
	
/*	fprintf(stderr, "Writing %d bytes\n", (int) (*buflen)); */
	do
	{
		r = write(self->fd, buf, *buflen);
	}
	while(-1 == r && EINTR == errno);
	if(-1 == r)
	{
		return errno;
	}
	/* Return the number of bytes remaining in *buflen */
	*buflen -= r;
	return COM_S_OK;
}

static com_result_t __stdcall
UStream_FD_Read(IUStreamNode *intf, IUStream *stream, void *buf, size_t *buflen)
{
	ssize_t r;

	DECLARE_SELF(UStream_FD, IUStreamNode, intf);

	(void) stream;

	do
	{
		r = read(self->fd, buf, *buflen);
	}
	while(-1 == r && EINTR == errno);
	if(-1 == r)
	{
		return errno;
	}
	if(0 == r)
	{
		/* We've reached the end of file. To differentiate between
		 * "end of file" and "no payload", UStream classes explicitly
		 * return EPIPE on end-of-file.
		 * As we just wrap a file descriptor, we have no need
		 * to actually make the distinction; higher-level modules will
		 * do, however.
		 */
		return EPIPE;
	}
	*buflen -= r;
	return COM_S_OK;
}

static com_result_t __stdcall
UStream_FD_Accept(IUStreamNode *intf, IUStream *stream, IUStreamNode **out, int *fdout)
{
	UStream_FD *f;
	struct sockaddr *sa;
	socklen_t slen;
	
	DECLARE_SELF(UStream_FD, IUStreamNode, intf);
	
	/* As this is a head node, we accept a connection directly and encapsulate it in
	 * a UStream_FD instance.
	 */
	if(NULL == (sa = (struct sockaddr *) alloca(SOCK_MAXADDRLEN)))
	{
		return errno;
	}
	if(NULL == (f = (UStream_FD *) calloc(1, sizeof(UStream_FD))))
	{
		return errno;
	}
	slen = SOCK_MAXADDRLEN;
	if(-1 == (f->fd = accept(self->fd, sa, &slen)))
	{
		free(f);
		return errno;
	}
	INITIALISE_ADDREF_INTERFACE_POINTER(UStream_FD, f, IUStreamNode);
	*out = GET_INTERFACE_POINTER(f, IUStreamNode);
	*fdout = f->fd;
	return COM_S_OK;
}

static com_result_t __stdcall
UStream_FD_Pending(IUStreamNode *intf, IUStream *stream, size_t *out)
{
	int len;
	
	DECLARE_SELF(UStream_FD, IUStreamNode, intf);
	
	if(-1 == ioctl(self->fd, FIONREAD, &len))
	{
		return errno;
	}
	*out = (size_t) len;
	return COM_S_OK;
}
